<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:modelValue']);

const avatarUrl = ref(props.modelValue || '');
const fileInput = ref(null);

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  avatarUrl.value = newValue;
});

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.includes('image/')) {
    alert('请上传图片文件');
    return;
  }
  
  // 验证文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    alert('图片大小不能超过2MB');
    return;
  }
  
  // 读取文件并转换为base64
  const reader = new FileReader();
  reader.onload = (e) => {
    avatarUrl.value = e.target.result;
    emit('update:modelValue', e.target.result);
  };
  reader.readAsDataURL(file);
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 移除头像
const removeAvatar = () => {
  avatarUrl.value = '';
  emit('update:modelValue', '');
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};
</script>

<template>
  <div class="flex flex-col items-center">
    <div 
      class="relative w-24 h-24 mb-2 rounded-full overflow-hidden bg-gray-200 cursor-pointer"
      @click="triggerFileInput"
    >
      <img 
        v-if="avatarUrl" 
        :src="avatarUrl" 
        alt="用户头像" 
        class="w-full h-full object-cover"
      />
      <div 
        v-else 
        class="w-full h-full flex items-center justify-center text-gray-500"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
        </svg>
      </div>
      
      <div 
        v-if="avatarUrl" 
        class="absolute inset-0 bg-black bg-opacity-40 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity"
      >
        <span class="text-white text-sm">更换头像</span>
      </div>
    </div>
    
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      class="hidden"
      @change="handleFileChange"
    />
    
    <div class="flex space-x-2">
      <button 
        type="button" 
        class="text-sm text-blue-600 hover:text-blue-800"
        @click="triggerFileInput"
      >
        {{ avatarUrl ? '更换头像' : '上传头像' }}
      </button>
      
      <button 
        v-if="avatarUrl" 
        type="button" 
        class="text-sm text-red-600 hover:text-red-800"
        @click="removeAvatar"
      >
        移除
      </button>
    </div>
  </div>
</template>